package cn.edu.suse.epilepsy.interceptor;

import cn.edu.suse.epilepsy.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: QingShu
 * @Date: 2024/7/5 15:57
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取Authorization字段
        String token = request.getHeader("Authorization");

        if (token == null || !JwtUtil.verifyToken(token)) {
            // 设置响应状态码为401 Unauthorized
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");

            // 创建返回的错误信息
            Map<String, Object> errorData = new HashMap<>();
            errorData.put("code", 401);
            errorData.put("msg", "未授权或无效的令牌");

            // 使用Jackson的ObjectMapper将map转换为json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(errorData);

            // 将错误信息写入响应
            response.getWriter().write(jsonResponse);
            return false;
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
